<template>
	<base-page title="添加活动商品" backgroundColor="white">
		<view class="mt-16 mx-16 mb-8 flex-shrink">
			<text class="fs-16">请选择活动商品</text>
		</view>
		<view class="flex item-center radius-8 bg-default h-38 px-16 py-0 mx-16 mb-12 flex-shrink" @click="toSearch">
			<image class="w-20 h-20 mr-5" src="@/static/svg/icon-search.svg"></image>
			<text class="fs-12 text-color-hint">搜商品</text>
		</view>
		<view class="flex-1 flex">
			<scroll-view ref="navScrollView" class="flex-shrink h-full" style="width:80px;" scroll-y="true">
				<view class="flex item-center px-12 py-10 fs-12 font-normal leading-22" :style="currentNav===0?'color:#333333;border-radius:0px 8px 8px 0px;background:#FFF;':'color:#666;background:#F2F2F2;'" @click="onNavItemClick(null, 0)">
					<uni-badge :text="selectedList.filter(it => it.mulState!==2).length" size="small" :offset="[-6,0]" absolute="rightTop" :customStyle="{background: '#FA4543'}">
						<text>已选</text>
					</uni-badge>
				</view>
				<view v-for="(item, i) in merchantList" :key="i+1" class="flex item-center px-12 py-10 fs-12 font-normal leading-22" :style="currentNav===i+1?'color:#333;border-radius:0 8px 8px 0;background:#FFF;':'background:#F2F2F2;'" @click="onNavItemClick(item, i+1)">
					<uni-badge :text="selectedMerchantGoodsNum(item)" size="small" :offset="[-6,0]" absolute="rightTop" :customStyle="{background: '#FA4543'}">
						<text>{{item.merchantShortName}}</text>
					</uni-badge>
				</view>
			</scroll-view>
			<view class="flex-1 ml-16">
				<scroll-view scroll-y="true">
					<template v-if="currentNav===0">
						<view v-for="(item,i) in selectedList.filter(it => it.mulState!==2)" :key="i" class="mr-16 mb-16">
							<view class="flex">
								<view class="flex">
									<view class="flex item-center">
										<image class="w-16 h-16 mr-4" src="@/static/svg/activity/icon-radio-delete.svg" @click="deleteSelected(item)"></image>
										<view class="relative mr-12">
											<image class="radius-12" style="width:64px;height:64px;" :src="item.goodsImgs"></image>
											<view v-if="item.verifyType===1" class="inline-flex absolute w-32 h-19" style="left:-5px;top:0;">
												<image class="w-32 h-19" src="@/static/svg/pft-ticket.svg"></image>
												<text class="absolute fs-8 font-normal text-color-regular" style="left:4px;top:2px;">票付通</text>
											</view>
										</view>
									</view>
								</view>
								<view class="mb-6">
									<view class="mb-4"><text class="text-color-regular fs-14 font-semibold">{{item.goodsName}}</text></view>
									<view><text class="color-primary fs-14 font-semibold"><text class="fs-11">¥</text>{{item.goodsPrice}}</text></view>
								</view>
							</view>
							<view class="flex justify-end item-center">
								<view class="mr-15">
									<text class="text-color-hint fs-10 font-normal">可用库存:{{item.remainStock}}</text>
								</view>
								<view>
									<number-input-box :value="item.goodsNum" :min="1" :max="item.remainStock" @change="onSelectChange(item, $event)"></number-input-box>
								</view>
							</view>
						</view>
					</template>
					<template v-else>
						<view v-for="(item,i) in currentGoodsList" :key="i" class="mr-16 mb-16">
							<view class="flex">
								<view class="flex">
									<view class="flex item-center">
										<image v-if="hasChecked(item)" class="w-16 h-32 py-8 mr-4" src="@/static/svg/activity/icon-radio-check-blue.svg" @click="noCheck(item)"></image>
										<image v-else class="w-16 h-32 py-8 mr-4" src="@/static/svg/activity/icon-radio-default.svg" @click="check(item)"></image>
										<view class="relative mr-12">
											<image class="radius-12" style="width:64px;height:64px;" :src="item.goodsImgs"></image>
											<view v-if="item.verifyType===1" class="inline-flex absolute w-32 h-19" style="left:-5px;top:0;">
												<image class="w-32 h-19" src="@/static/svg/pft-ticket.svg"></image>
												<text class="absolute fs-8 font-normal text-color-regular" style="left:4px;top:2px;">票付通</text>
											</view>
										</view>
									</view>
								</view>
								<view class="mb-6">
									<view class="mb-4"><text class="text-color-regular fs-14 font-semibold">{{item.goodsName}}</text></view>
									<view><text class="color-primary fs-14 font-semibold"><text class="fs-11">¥</text>{{item.goodsPrice}}</text></view>
								</view>
							</view>
							<view class="flex justify-end item-center">
								<view class="mr-15">
									<text class="text-color-hint fs-10 font-normal">可用库存:{{item.remainStock}}</text>
								</view>
								<view>
									<number-input-box v-if="hasChecked(item)" :value="item.goodsNum || 1" :min="1" :max="item.remainStock" @change="onSelectChange(item, $event)"></number-input-box>
								</view>
							</view>
						</view>
					</template>
				</scroll-view>
			</view>
		</view>
		<template #footer>
			<view class="m-12 flex">
				<button class="flex-1 flex center radius-8 h-46 fs-16 uni-bg-white text-color-hint mr-12" style="border:1px solid rgba(51, 51, 51, 0.60);" @click="goBack">取消</button>
				<button class="flex-1 flex center radius-8 h-46 fs-16 bg-primary text-white" @click="submit">确认</button>
			</view>
		</template>
	</base-page>
</template>

<script setup name="AddGoods">
	import { onLoad, onShow } from '@dcloudio/uni-app'
	import {
		onMounted,
		ref,
		unref,
		getCurrentInstance,
		toRaw,
	} from 'vue'
	import {
		getRelationMerchantApi,
		getGoodsActiveApi
	} from '@/api/activity.js'
	import { getActiveLimitApi } from '@/api/business.js'
	import { usePublishStore } from '@/stores/modules/publish.js'
	
	const publishStore = usePublishStore()

	const instance = getCurrentInstance()

	const goBack = () => uni.navigateBack()
	
	const currentNav = ref(0)
	const selectedList = ref(publishStore.tempGoodsList.map(it => toRaw({...it})))
	
	const navScrollView = ref(null)
	const navScrollIntoView = ref('')
	const contentScrollView = ref(null)
	const contentScrollIntoView = ref('')
	let singleActiveMerchantCount = 0
	
	const getActiveCount = () => {
		getActiveLimitApi().then(res => {
			singleActiveMerchantCount = res.singleActiveMerchantCount
		})
	}
	
	const toSearch = () => {
		uni.navigateTo({
			url: '/pagesG/publish/search-goods',
			success: (res) => {
				res.eventChannel.emit('acceptDataFromOpenerPage', {
					selectedList: selectedList.value.map(it => toRaw({...it}))
				})
			},
			events: {
				onGoodsSelect: (list) => {
					selectedList.value = list
					for (var i = 0; i < selectedList.value.length; i++) {
						const obj = selectedList.value[i]
						obj.mulState = 1 // 商品
						obj.goodsId = +obj.goodsId // 商品ID
						for (var j = 0; j < currentGoodsList.value.length; j++) {
							const element = currentGoodsList.value[j]
							if (obj.goodsId === element.id) {
								element.goodsNum = obj.goodsNum
							}
						}
					}
				}
			}
		})
	}

	const onNavItemClick = (item, index) => {
		if (currentNav.value !== index) {
			currentNav.value = index
			if (index !== 0) {
				queryParams.value.merchantId = item.id
				queryParams.value.pageNum = 1
				getGoodsActive()
			}
		}
		// contentScrollIntoView.value = `id_${item.id}`
	}
	
	// 勾选
	const check = (item) => {
		const obj = selectedList.value.find(it => it.goodsId && +it.goodsId === item.id)
		let currentIds = []
		selectedList.value.forEach(item => {
			currentIds.push(item.merchantId)
		})
		let ids = [...new Set([...publishStore.merchantIds, ...currentIds])]
		if (!obj) {
			if(singleActiveMerchantCount && singleActiveMerchantCount <= ids.length && !ids.includes(item.merchantId)){
				uni.showToast({
					icon: 'none',
					title: `活动仅限${singleActiveMerchantCount}个商户参与`
				})
				return
			}
			item.mulState = 1 // 商品
			item.goodsId = item.id // 商品ID
			item.goodsNum = 1
			selectedList.value.push(item)
		}
	}
	
	// 取消勾选
	const noCheck = (item) => {
		selectedList.value = selectedList.value.filter(it => it.goodsId && +it.goodsId !== item.id)
		item.goodsNum = 0
	}
	
	// 删除已选
	const deleteSelected = (item) => {
		selectedList.value = selectedList.value.filter(it => it.goodsId && +it.goodsId !== item.id)
	}
	
	// 是否添加过
	const hasChecked = (item) => {
		return selectedList.value.some(it => it.goodsId && +it.goodsId === item.id)
	}
	
	const onSelectChange = (item, val) => {
		const obj = selectedList.value.find(it => it.goodsId && +it.goodsId === item.id)
		console.log('修改库存', item, val, obj, selectedList.value)
		if (obj) {
			obj.goodsNum = val
		}
		item.goodsNum = val
	}
	
	// 商户被选中的商品数
	const selectedMerchantGoodsNum = (item) => {
		return selectedList.value.reduce((pre, cur) => {
			return pre + (cur.merchantId === item.id ? 1 : 0 )
		}, 0)
	}
	
	const submit = () => {
		if (selectedList.value.length) {
			publishStore.goodsList = [...selectedList.value]
			uni.navigateBack()
		} else {
			uni.showToast({
				icon: 'none',
				title: '请选择要添加的活动商品'
			})
		}
	}

	let observer
	let visiableIds = ref([])
	
	const queryParams = ref({
		merchantId: null,
		pageNum: 1,
		pageSize: 5000,
	})
	const currentGoodsList = ref([])
	const getGoodsActive = () => {
		getGoodsActiveApi(unref(queryParams)).then(res => {
			currentGoodsList.value = res.list || []
			if (selectedList.value.length) {
				for (var i = 0; i < selectedList.value.length; i++) {
					const obj = selectedList.value[i]
					for (var j = 0; j < currentGoodsList.value.length; j++) {
						const element = currentGoodsList.value[j]
						if (+obj.goodsId === element.id) {
							element.goodsNum = obj.goodsNum
						}
					}
				}
			}
		})
	}
	
	const merchantList = ref([])
	const getRelationMerchant = () => {
		getRelationMerchantApi({
			pageNum: 1,
			pageSize: 5000,
		}).then(res => {
			const list = res.list || []
			merchantList.value = list
			if (list.length) {
				currentNav.value = 1
				queryParams.value.merchantId = list[0].id
				queryParams.value.pageNum = 1
				getGoodsActive()
			}
		})
	}
	
	onShow(() => {
		getActiveCount()
	})
	
	onMounted(() => {
		getRelationMerchant()
		observer = uni.createIntersectionObserver(instance, {
			observeAll: true
		})
	})
</script>
